<template>
	<view>
		<cu-custom bgColor="bg-grey light" :isBack="true">
			<view slot="backText">返回</view>
			<view slot="content">我的课表</view>
		</cu-custom>

		<loginModal :showLoginModal.sync="isLoginModalShow" @loginModalConfirm="loginModalConfirm"></loginModal>

		<view :style="'position: fixed;right: 0;bottom: 0;left: 0;top:' + CustomBar + 'px;'">
			<view>
				<view class="flex justify-center padding-sm text-center">
					<view :class="'load-progress ' + (loadProgress != 0 ? 'show' : 'hide')"
						:style="'top:' + CustomBar + 'px;'">
						<view class="load-progress-bar bg-black"
							:style="'transform: translate3d(-' + (100 - loadProgress) + '%, 0px, 0px)'"></view>
						<view class="load-progress-spinner text-black"></view>
					</view>
					<view class="margin-lr-sm">
						<button class="cu-btn icon round line-orange" @tap="toLastWeek" role="button"
							:aria-disabled="false">
							<text class="cuIcon-back text-xl"></text>
						</button>
					</view>
					<view>
						<button class="line-cayan cu-btn" role="button" @tap="refreshData" :aria-disabled="false">
							<text class="text-df">刷新</text>
						</button>
					</view>
					<view class="margin-lr-sm">
						<button style="width: 200rpx" class="line-blue cu-btn" role="button" :aria-disabled="false">
							<picker @change="pickerChangeTopWeek" :value="nowWeek" :range="weekArrAll">
								<text class="text-df">{{ weekArrAll[nowWeek] }}</text>
							</picker>
						</button>
					</view>
					<view>
						<button class="line-pink cu-btn" @tap="showSetting" role="button" :aria-disabled="false">
							<text class="text-df">设置</text>
						</button>
					</view>
					<view class="margin-lr-sm">
						<button class="cu-btn icon round line-orange" @tap="toNextWeek" role="button"
							:aria-disabled="false">
							<text class="cuIcon-right text-xl"></text>
						</button>
					</view>
				</view>
			</view>

			<view
				:style="'height:100%;background-image:url(' + backGroundImg + ');background-repeat:no-repeat;background-size:auto 100%;'">
				<view style="height: 100%">
					<view style="background-color: #f1f1f1; opacity: 0.9; padding-top: 12rpx">
						<view class="flex solid-bottom">
							<view style="width: 32rpx; padding-top: 0rpx">
								<view class="grid col-1 kebiao text-center">
									<view class="">{{ month }}月</view>
								</view>
							</view>
							<view style="flex: 10">
								<view class="grid col-7 text-center">
									<view v-for="(item, index) in weekArrTop" :key="index">
										<view :class="
                                                'grid col-1 light text-center ' +
                                                (item === nowDay && month === nowMonth && year === nowYear ? 'bg-brown radius' : '')
                                            ">
											<view>{{ weekArr[index] }}</view>
											<view>{{ item }}日</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>

					<view style="height: 100%; overflow: scroll">
						<view class="flex kebiao-content">
							<view class="bg-grey light"
								style="width: 35rpx; opacity: 0.8 !important; margin-right: 3rpx">
								<view class="grid col-1 kebiao-left text-center">
									<view>1</view>
									<view>2</view>
									<view>3</view>
									<view>4</view>
									<view>5</view>
									<view>6</view>
									<view>7</view>
									<view>8</view>
									<view>9</view>
									<view>10</view>
								</view>
							</view>
							<view style="flex: 10">
								<view v-if="days && isThisWeek" class="grid col-7 text-center">
									<view class="grid col-1 text-center" v-for="(item, currentDay) in 7"
										:key="currentDay">
										<view class="course_tag0" v-for="(item, currentClass) in 10"
											:key="currentClass">

											<view v-for="(item, index) in days[currentDay][currentClass]" :key="index"
												v-if="item.startClass == currentClass + 1 && nowWeek >= item.startWeek && nowWeek <= item.endWeek"
												class="course_tag2" :style="'height:' + item.length * biaoZhun + 'px'">
												<view
													:class="'course_tag3  bg-' + ((currentDay + currentClass) % 9) + ' radius text-sm '"
													:data-id="[currentDay, currentClass, index]" @tap="showDetail">
													<view class="text-cut" style="height: 40rpx">{{ item.name }}
													</view>
													<view>{{ item.where }}</view>
												</view>
											</view>

										</view>
									</view>
								</view>

								<view v-if="days && !isThisWeek" class="grid col-7 text-center">
									<view class="grid col-1 text-center" v-for="(item, currentDay) in 7"
										:key="currentDay">
										<view class="course_tag0" v-for="(item, currentClass) in 10"
											:key="currentClass">


											<view v-if="days[currentDay][currentClass].length == 1" class="course_tag2"
												:style="'height:' + days[currentDay][currentClass][0].length * biaoZhun + 'px'">
												<view
													:class="'course_tag3  bg-' + ((currentDay + currentClass) % 9) + ' radius text-sm '"
													:data-id="[currentDay, currentClass, 0]" @tap="showDetail">

													<view class="text-cut" style="height: 40rpx">
														{{ days[currentDay][currentClass][0].name }}
													</view>
													<view>{{ days[currentDay][currentClass][0].where }}</view>
												</view>


											</view>

											<view class="course_tag2" v-if="days[currentDay][currentClass].length > 1"
												:style="'height:' + days[currentDay][currentClass][0].length * biaoZhun + 'px'">

												<view
													:class="'course_tag3 bg-' + ((currentDay + currentClass) % 9) + ' radius text-sm'"
													:data-id="[currentDay, currentClass]" @tap="showChooseCourse">
													<view class="text-cut" style="height: 40rpx"
														v-for="(item, index) in days[currentDay][currentClass]"
														:key="index">
														{{ item.name }}
													</view>
													<view text-bold>*有多节</view>
												</view>
											</view>



										</view>
									</view>
								</view>

							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view :class="'cu-modal ' + (isSettingShow ? 'show' : '')">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">设置</view>
					<view class="action" @tap="hideSetting">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="">
					<view class="grid col-1 margin-bottom text-center">
						<view class="cu-form-group">
							<view class="title">只显示本周</view>
							<switch @change="changeIsThisWeek" :checked="isThisWeekTemp" class="red sm"></switch>
						</view>
						<view class="cu-form-group">
							<view class="title">设置背景图片</view>
							<view @tap="changeDefaultImg" class="text-sm margin-left-sm text-grey">
								<text>恢复默认</text>
							</view>
							<view @tap="chooseImg" class="cu-avatar radius bg-gray"
								:style="'background-image:url(' + backGroundImgTemp + ');'"></view>
						</view>
						<view class="cu-form-group">
							<view class="title">选择学期</view>
							<picker mode="multiSelector" @change="changeTerm" :value="termTemp" :range="termArr">
								<view class="picker">
									{{ termArr[0][termTemp[0]] }}，{{ termArr[1][termTemp[1]] }}
								</view>
							</picker>
						</view>
						<view class="cu-form-group">
							<view class="title">设置当前周数</view>
							<picker mode="selector" @change="changeNowWeek" :value="nowWeekTemp" :range="weekArrAll">
								<view class="picker">
									{{ weekArrAll[nowWeekTemp] }}
								</view>
							</picker>
						</view>
					</view>
				</view>
				<view class="cu-bar bg-white justify-end">
					<view class="action">
						<button class="cu-btn line-black text-green" @tap="hideSetting">取消</button>
						<button class="cu-btn bg-black margin-left" @tap="confirmChange">确定</button>
					</view>
				</view>
			</view>
		</view>

		<view :class="'cu-modal ' + (isDetailShow ? 'show' : '')">
			<view class="cu-dialog bg-white" style="width: 500rpx">
				<view class="cu-bar bg-white justify-end">
					<view class="content">课程详情</view>
					<view class="action" @tap="hideDetail">
						<text class="cuIcon-close text-purple"></text>
					</view>
				</view>
				<view class="bg-white">
					<view class="action text-lg text-bold padding-sm text-left">
						<text class="cuIcon-title text-cyan margin-lr-lg"></text>
						{{ detailName }}
					</view>
					<view class="action text-lg padding-sm text-left">
						<text class="cuIcon-location text-orange margin-lr-lg"></text>
						{{ detailWhere }}
					</view>
					<view class="action text-lg padding-sm text-left">
						<text class="cuIcon-calendar text-purple margin-lr-lg"></text>
						{{ detailWeekInfo }}
					</view>
					<view class="action text-lg padding-sm text-left">
						<text class="cuIcon-info text-pink margin-lr-lg"></text>
						{{ detailCourseInfo }}
					</view>
					<view class="action text-lg padding-sm margin-bottom-lg text-left">
						<text class="cuIcon-friendfamous text-blue margin-lr-lg"></text>
						{{ detailTeacher }}
					</view>
				</view>
			</view>
		</view>

		<view :class="'cu-modal ' + (isChooseCourseShow ? 'show' : '') ">
			<view class="cu-dialog bg-white">
				<view class="cu-bar bg-white justify-end">
					<view class="content">选择课程</view>
					<view class="action" @tap="hideChooseCourse">
						<text class="cuIcon-close text-purple"></text>
					</view>
				</view>
				<view :class="'bg-white grid col-' + moreCourseArr.length + ' text-center'">
					<view class="padding" v-for="(item, index) in moreCourseArr" :key="item.key">
						<view @tap="showDetail" :data-id="[choosedWeek, choosedClass, index]" :class="
							'bg-' +
							(item.startClass == choosedClass + 1 ? (nowWeek >= item.startWeek ? (nowWeek <= item.endWeek ?
								index % 8 : 'grey' ) : 'grey' ) : 'grey' )
								+ '  padding light  radius text-center text-df shadow-blur' " style=" height: 200rpx">
							<view class="text-cut" style="height: 40rpx">{{ item.name }}</view>
							<view class="more0">{{ item.where }}</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import loginModal from '@/pages/login-modal/index'
	import {
		getDays
	} from '../../utils/getKebiao.js'
	const app = getApp();
	export default {
		components: {
			loginModal,
		},
		data() {
			return {
				CustomBar: app.globalData.CustomBar,
				isLoginModalShow: false,
				nowMonth: new Date().getMonth() + 1,
				nowYear: new Date().getFullYear(),
				nowDay: new Date().getDate(),
				nowWeek: 0,
				nowWeekTemp: 0,
				weekBegin: 0,
				weekStartTemp: 0,
				month: '',
				year: '',
				nowDate: '',
				weekArrTop: '',
				weekArr: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
				weekArrAll: [
					'未开始',
					'第一周',
					'第二周',
					'第三周',
					'第四周',
					'第五周',
					'第六周',
					'第七周',
					'第八周',
					'第九周',
					'第十周',
					'第十一周',
					'第十二周',
					'第十三周',
					'第十四周',
					'第十五周',
					'第十六周',
					'第十七周',
					'第十八周',
					'第十九周',
					'第二十周',
					'第二十一周',
					'第二十二周',
					'第二十三周',
					'第二十四周',
					'第二十五周',
					'假期中'
				],
				termArr: [
					['', '', '', ''],
					['', '']
				],
				term: [3, 0],
				termTemp: [3, 0],
				isSettingShow: false,
				isThisWeek: true,
				isThisWeekTemp: true,
				loadProgress: 0,
				isDetailShow: false,
				detailWhere: '',
				detailWeekInfo: '',
				detailCourseInfo: '',
				detailTeacher: '',
				detailName: '',
				isChooseCourseShow: false,
				moreCourseArr: '',
				backGroundImgTemp: '',
				backGroundImg: '',
				isLoad: false,
				biaoZhun: '',
				days: false
			};
		},

		onLoad: function(options) {
			let that = this
			uni.getStorage({
				key: 'userID',
				fail() {
					uni.redirectTo({
						url: '/pages/login/index'
					});
				},
				success() {
					that.doSuccess();
				}
			});
		},

		methods: {
			doSuccess() {
				let that = this;
				let nowDate = new Date();
				let nowYear = nowDate.getFullYear();
				let nowMonth = nowDate.getMonth();
				let k = nowMonth > 6 ? 0 : 1;
				uni.getStorage({
					key: 'keBiaoData',
					fail() {
						that.setData({
							isThisWeek: true,
							term: [3, k]
						});
						that.showSetting();
						return
					}
				});


				let windowHeigth = uni.getSystemInfoSync().windowHeight
				let biaoZhun;
				if (windowHeigth > 0 && windowHeigth <= 570) {
					biaoZhun = 40;
				} else if (windowHeigth > 570 && windowHeigth <= 800) {
					biaoZhun = 50;
				} else if (windowHeigth > 800 && windowHeigth <= 900) {
					biaoZhun = 60;
				} else {
					biaoZhun = 100;
				}

				this.keBiaoDataWeekBegin = uni.getStorageSync('keBiaoDataWeekBegin');
				this.weekStartTemp = new Date(new Date().toLocaleDateString()).getTime() - ((new Date().getDay() == 0 ? 7 :
					new Date().getDay()) - 1) * 86400000;

				if (this.keBiaoDataWeekBegin == '') {
					this.keBiaoDataWeekBegin = this.weekStartTemp;
					uni.setStorageSync('keBiaoDataWeekBegin', this.weekStartTemp);
				}

				let timeTemp = new Date().getTime();
				this.getDates(timeTemp);
				let weekTemp = Math.ceil((timeTemp - this.keBiaoDataWeekBegin) / 604800000);

				if (weekTemp > 26) {
					weekTemp = 26;
				}

				let termArr = [new Array(4), ["第一学期", "第二学期"]];
				for (let i = 0; i < 4; i++) {
					termArr[0][i] = nowYear - (3 - i) - k + '-' + (nowYear + (i - 2) - k);
				}

				this.setData({
					days: uni.getStorageSync('keBiaoData'),
					isThisWeek: uni.getStorageSync('keBiaoSetIsThisWeek'),
					term: uni.getStorageSync('keBiaoSetTerm'),
					keBiaoDataWeekBegin: uni.getStorageSync('keBiaoDataWeekBegin'),
					backGroundImg: uni.getStorageSync('keBiaoSetBackGroundImg'),
					nowWeek: weekTemp,
					nowWeekTemp: weekTemp,
					nowDate: timeTemp,
					biaoZhun,
					termArr
				});

				console.log(this.days)
			},


			getDates(currentTime) {
				let currentDate = new Date(currentTime);
				let timesStamp = currentDate.getTime();
				let currenDay = currentDate.getDay();
				let month = currentDate.getMonth() + 1;
				let year = currentDate.getFullYear();
				let dates = [];

				for (let i = 0; i < 7; i++) {
					dates.push(new Date(timesStamp + 24 * 60 * 60 * 1000 * (i - ((currenDay + 6) % 7))).getDate());
				}

				this.setData({
					weekArrTop: dates,
					nowDate: currentTime,
					month: month,
					year: year
				});
			},

			loginModalConfirm(e) {
				this.refreshData()
			},

			pickerChangeTopWeek(e) {
				let temp;

				if (this.nowWeek < parseInt(e.detail.value)) {
					temp = parseInt(e.detail.value) - this.nowWeek;
					this.getDates(this.nowDate + 604800000 * temp);
					this.setData({
						nowWeek: this.nowWeek + temp
					});
				} else if (this.nowWeek > parseInt(e.detail.value)) {
					temp = this.nowWeek - parseInt(e.detail.value);
					this.getDates(this.nowDate - 604800000 * temp);
					this.setData({
						nowWeek: this.nowWeek - temp
					});
				}
			},

			changeTerm(e) {
				this.setData({
					termTemp: e.detail.value
				});
			},

			changeNowWeek(e) {
				this.setData({
					nowWeekTemp: e.detail.value
				});
			},

			loadProgressFun() {
				this.setData({
					loadProgress: this.loadProgress + 3
				});

				if (this.loadProgress < 100) {
					setTimeout(() => {
						this.loadProgressFun();
					}, 100);
				} else {
					this.setData({
						loadProgress: 0
					});
				}
			},

			async refreshData() {
				this.loadProgressFun();
				let that = this;
				uni.showLoading({
					title: '正在获取中'
				});

				let term0 = this.termArr[0][this.term[0]];
				let term1;

				if (this.term[1] == 0) {
					term1 = '-1-1';
				} else {
					term1 = '-2-1';
				}

				let res = await getDays(term0, term1)
				console.log(res)
				uni.hideLoading()
				if (res == null) {
					that.showLoginModal();
					that.setData({
						isLoad: false
					});
					return
				}

				uni.showToast({
					title: '获取成功'
				});

				uni.setStorageSync('keBiaoData', res);
				that.setData({
					days: res,
					isLoad: false,
					nowWeek: 1,
					nowWeekTemp: 1
				});
				console.log(this.days)
				uni.setStorageSync('keBiaoDataWeekBegin', that.weekStartTemp);
				that.keBiaoDataWeekBegin = that.weekStartTemp;
			},

			toNextWeek() {
				if (parseInt(this.nowWeek) > 25) {
					return;
				}

				this.getDates(this.nowDate + 604800000);
				this.setData({
					nowWeek: parseInt(this.nowWeek) + 1
				});
			},

			toLastWeek() {
				if (this.nowWeek == 0) {
					return;
				}

				this.getDates(this.nowDate - 604800000);
				this.setData({
					nowWeek: parseInt(this.nowWeek) - 1
				});
			},


			showLoginModal() {
				this.setData({
					isLoginModalShow: true
				});
			},

			showSetting() {
				this.setData({
					isThisWeekTemp: this.isThisWeek,
					termTemp: this.term,
					backGroundImgTemp: this.backGroundImg,
					isSettingShow: true,
				});
			},

			confirmChange() {
				if (this.term[0] != this.termTemp[0] || this.term[1] != this.termTemp[1]) {
					this.setData({
						term: this.termTemp,
					});
					this.refreshData();
				}

				let timeTemp = new Date().getTime();
				this.getDates(timeTemp);
				uni.setStorageSync('keBiaoSetTermArr', this.termArr);
				uni.setStorageSync('keBiaoSetTerm', this.termTemp);
				uni.setStorageSync('keBiaoSetIsThisWeek', this.isThisWeekTemp);
				uni.setStorageSync('keBiaoDataWeekBegin', this.weekStartTemp - (this.nowWeekTemp - 1) * 604800000);
				this.keBiaoDataWeekBegin = this.weekStartTemp - (this.nowWeekTemp - 1) * 604800000;
				let that = this;
				this.setData({
					isThisWeek: this.isThisWeekTemp,
					nowWeek: this.nowWeekTemp
				})
				if (that.backGroundImgTemp == '') {
					this.setData({
						backGroundImg: ''
					});
				}

				uni.removeSavedFile({
					filePath: uni.getStorageSync('keBiaoSetBackGroundImg'),
					success() {
						console.log('旧背景图已删除');
					},
					complete(res) {
						console.log(res);
					}
				});
				uni.saveFile({
					tempFilePath: that.backGroundImgTemp,
					success(res) {
						console.log(res.savedFilePath);
						that.setData({
							backGroundImg: res.savedFilePath
						});
						uni.setStorageSync('keBiaoSetBackGroundImg', res.savedFilePath);
					},
					fail(err) {
						console.log(err);
					}
				});
				uni.getStorage({
					key: 'keBiaoData',
					fail: function(res) {
						that.refreshData();
					}
				});
				this.hideSetting();
			},


			hideSetting() {
				this.setData({
					isSettingShow: false
				});
			},

			showDetail(e) {
				let currentDay = e.currentTarget.dataset.id[0]
				let currentClass = e.currentTarget.dataset.id[1]
				let currentNum = e.currentTarget.dataset.id[2]
				let currentDetail = this.days[currentDay][currentClass][currentNum]
				this.setData({
					isDetailShow: true,
					detailName: currentDetail.name,
					detailWhere: currentDetail.where,
					detailCourseInfo: currentDetail.startWeek + '-' + currentDetail.endWeek + ' 周',
					detailWeekInfo: this.weekArrAll[currentDay] + ' ' + currentClass + '-' + (currentDetail
						.startClass +
						currentDetail.length - 1) + ' 节',
					detailTeacher: currentDetail.teacher,
					isChooseCourseShow: false
				});
			},

			hideDetail(e) {
				this.setData({
					isDetailShow: false,
				});
			},

			changeIsThisWeek(e) {
				this.isThisWeekTemp = e.detail.value;
			},


			showChooseCourse(e) {
				let currentDay = e.currentTarget.dataset.id[0]
				let currentClass = e.currentTarget.dataset.id[1]
				let courses = this.days[currentDay][currentClass];
				this.setData({
					moreCourseArr: courses,
					choosedWeek: currentDay,
					choosedClass: currentClass,
					isChooseCourseShow: true
				});
			},

			hideChooseCourse() {
				this.setData({
					isChooseCourseShow: false
				});
			},

			chooseImg() {
				let that = this;
				let device = uni.getSystemInfoSync();
				let rate = device.pixelRatio;
				let cropWidth = device.windowWidth * 0.8;
				let cropHeight = (device.windowHeight - app.globalData.CustomBar) * 0.8;
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album'],
					success: function(res) {
						if (res.tempFilePaths.count == 0) {
							return;
						}
						console.log(res)
						uni.navigateTo({
							url: '/pages/cropper/index?url=' + res.tempFilePaths[0] + '&width=' +
								cropWidth + '&height=' + cropHeight,
							events: {
								getNew: function(data) {
									console.log(data.src);
									that.setData({
										backGroundImgTemp: data.src
									});
								}
							}
						});
					}
				});
			},

			changeDefaultImg() {
				this.setData({
					backGroundImgTemp: ''
				});
			}
		}
	};
</script>
<style>
	@import './index.css';
</style>
